﻿<template>
  <div class="app-container">
    <div class="chart-title">档案管理</div>
    <div class="chart-content">
      <div class="filter-title">
        <el-form label-position="right">
          <el-form-item>
            <el-input v-model="listQuery.equipment_name"
                      style="width: 160px; height:32px;"
                      class="filter-item"
                      :placeholder="$t('terminal.name')"
                      @keyup.enter.native="handleFilter"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input v-model="listQuery.maintain_name"
                      style="width: 160px; height:32px;"
                      class="filter-item"
                      :placeholder="$t('maintain.name')"
                      @keyup.enter.native="handleFilter"></el-input>
          </el-form-item>
          <el-form-item>
            <el-select v-model="listQuery.type"
                       style="width: 160px; height:32px;"
                       clearable
                       placeholder="请选择">
              <el-option v-for="item in typeOptions"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <div class="search-button"
               @click="handleFilter">
            <img src="@/assets/images/bg_search@2x.png" />
          </div>
          <div class="search-button"
               @click="handleRefresh">
            <img src="@/assets/images/bg_reset@2x.png" />
          </div>
          <div class="search-button"
               @click="searchItem">
            <img v-show="showSearchItem === true"
                 src="@/assets/images/bg_more@2x.png" />
            <img v-show="showSearchItem === false"
                 src="@/assets/images/bg_sx@2x.png" />
          </div>
        </el-form>
        <div class="filter-right">
          <div class="add-button"
               @click="handleCreate">
            <img src="@/assets/images/icon_add@2x.png" />
            <span>新建</span>
          </div>
        </div>
      </div>
      <div v-show="showSearchItem"
           class="filter-container">
        <el-form @submit.native.prevent>
          <el-form-item>
            <el-input v-model="listQuery.itoc_name"
                      style="width: 160px; height:32px;"
                      class="filter-item"
                      :placeholder="$t('public.itoc')"
                      @keyup.enter.native="handleFilter"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="chart-list">
        <el-table :key="tableKey"
                  v-loading="listLoading"
                  :data="list"
                  element-loading-text="拼命加载中"
                  element-loading-spinner="el-icon-loading"
                  element-loading-background="rgba(255,255,255,0.2)"
                  border
                  fit
                  highlight-current-row
                  style="width: 100%min-height:1000px">
          <el-table-column fixed="left"
                           align="center"
                           :label="$t('table.id')"
                           width="65">
            <template slot-scope="scope">
              <span>{{
                (listQuery.page - 1) * listQuery.limit + scope.$index + 1
              }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           show-overflow-tooltip
                           :label="$t('terminal.code')">
            <template slot-scope="scope">
              <span>{{ scope.row.equipment_code }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           show-overflow-tooltip
                           :label="$t('terminal.name')">
            <template slot-scope="scope">
              <span>{{ scope.row.equipment_name }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           show-overflow-tooltip
                           :label="$t('terminal.ip')">
            <template slot-scope="scope">
              <span>{{ scope.row.ip }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           show-overflow-tooltip
                           :label="$t('operations.name_2')">
            <template slot-scope="scope">
              <span>{{ scope.row.itoc_name }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           show-overflow-tooltip
                           :label="$t('maintain.name')">
            <template slot-scope="scope">
              <span>{{ scope.row.maintain_name }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           show-overflow-tooltip
                           :label="$t('public.mobile')">
            <template slot-scope="scope">
              <span>{{ scope.row.maintain_mobile }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           show-overflow-tooltip
                           :label="$t('fault.time')">
            <template slot-scope="scope">
              <span>{{ scope.row.create_time }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           show-overflow-tooltip
                           :label="$t('fault.type')">
            <template slot-scope="scope">
              <span>{{ faultTypeEs(scope.row.type) }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center"
                           show-overflow-tooltip
                           :label="$t('public.status')">
            <template slot-scope="scope">
              <span>{{ serviceStatus(scope.row.equipment_status) }}</span>
            </template>
          </el-table-column>

          <el-table-column align="center"
                           :label="$t('table.actions')"
                           class-name="small-padding fixed-width"
                           fixed="right">
            <template slot-scope="scope">
              <div class="read-img"
                   @click="handleRead(scope.row)">
                <img src="@/assets/images/read@2x.png" />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-container">
        <el-pagination background
                       :current-page="listQuery.page"
                       :page-sizes="[10, 20, 30, 50]"
                       :page-size="listQuery.limit"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="total"
                       @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"></el-pagination>
      </div>
      <!-- 编辑 -->
      <el-dialog :title="textMap[dialogStatus]"
                 :visible.sync="dialogFormVisible">
        <el-form ref="dataForm"
                 :rules="rules"
                 :model="temp"
                 label-position="right"
                 label-width="35%"
                 style="width: 400px margin-left:120px"
                 size="small">
          <div class="pops">
            <div class="information-title">
              <span class="icon-title"></span>
              <span>基础信息:</span>
            </div>
            <div class="pops-normal">
              <el-form-item :label="$t('terminal.name') + ' :'"
                            prop="equipment_id">
                <drop-down-select :data="terminalOptions"
                                  :count="terminalCount"
                                  :page-size="pageSize"
                                  :disabled="dialogStatus !== 'create'? true: false"
                                  :id="temp.equipment_id"
                                  :name="temp.equipment_name"
                                  @getList="(pageNumber, search)=>{return getTerminal(pageNumber, search,'getTerminal')}"
                                  @addList="(pageNumber, search)=>{return getTerminal(pageNumber, search,'addTerminal')}"
                                  @choose="(data)=>{return choose(data, 'terminal')}"
                                  @remove="(data)=>{return remove(data, 'terminal')}"></drop-down-select>
              </el-form-item>
              <el-form-item :label="$t('fault.type') + ' :'"
                            prop="type">
                <el-radio-group v-model="temp.type">
                  <el-radio :label="1"
                            :disabled="dialogStatus !== 'create' && temp.type !== 1  ? true : false">硬件故障</el-radio>
                  <el-radio :label="2"
                            :disabled="dialogStatus !== 'create' && temp.type !== 2  ? true : false">系统故障</el-radio>
                  <el-radio :label="3"
                            :disabled="dialogStatus !== 'create' && temp.type !== 3  ? true : false">网络故障</el-radio>
                  <el-radio :label="4"
                            :disabled="dialogStatus !== 'create' && temp.type !== 4  ? true : false">其他故障</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item :label="$t('fault.level') + ' :'"
                            prop="malfunction_level">
                <el-radio-group v-model="temp.malfunction_level">
                  <el-radio :label="1"
                            :disabled="dialogStatus !== 'create' && temp.malfunction_level !== 1  ? true : false">一级</el-radio>
                  <el-radio :label="2"
                            :disabled="dialogStatus !== 'create' && temp.malfunction_level !== 2  ? true : false">二级</el-radio>
                  <el-radio :label="3"
                            :disabled="dialogStatus !== 'create' && temp.malfunction_level !== 3  ? true : false">三级</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item :label="$t('fault.time') + ' :'"
                            prop="malfunction_time">
                <el-date-picker v-model="temp.malfunction_time"
                                type="datetime"
                                placeholder="选择日期时间"
                                :disabled="dialogStatus !== 'create'? true: false">
                </el-date-picker>
              </el-form-item>
              <el-form-item :label="$t('fault.describe') + ' :'"
                            prop="describe">
                <el-input type="textarea"
                          v-model="temp.describe"
                          :autosize="{ minRows: 2, maxRows: 6}"
                          placeholder="请输入内容"
                          :readonly="dialogStatus !== 'create'?true:false">
                </el-input>
              </el-form-item>
              <el-form-item :label="$t('public.pictrue') + ' :'"
                            prop="equipment_pic">
                <div class="avatar-uploader">
                  <div v-if="temp.equipment_pic">
                    <img :src="temp.equipment_pic"
                         class="avatar" />
                    <span class="el-upload-list__item-actions">
                      <span class="item-preview"
                            @click="previewPicture('equipment_pic')"><i class="el-icon-zoom-in"></i></span>
                      <span v-if="dialogStatus === 'create'"
                            class="item-delete"
                            @click="changPicture('equipment_pic')"><i class="el-icon-delete"></i></span>
                    </span>
                  </div>
                  <el-upload v-else
                             class="update-pic-icon"
                             action="#"
                             :show-file-list="false"
                             :http-request="
                      e => {
                        return updatePicture(e, 'equipment_pic');
                      }
                    ">
                    <i class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </div>
              </el-form-item>
              <el-form-item v-if="dialogStatus !== 'create'"
                            :label="$t('public.creationTime') + ' :'"
                            prop="create_time">
                <el-input v-model="temp.create_time"
                          :readonly="true"></el-input>
              </el-form-item>
              <el-form-item v-if="dialogStatus === 'edit' || temp.equipment_status"
                            :label="$t('public.status') + ' :'"
                            prop="equipment_status">
                <el-radio-group v-model="temp.equipment_status">
                  <el-radio :label="1"
                            :disabled="dialogStatus !== 'edit' && temp.equipment_status !== 1? true:false">待维修</el-radio>
                  <el-radio :label="2"
                            :disabled="dialogStatus !== 'edit' && temp.equipment_status !== 2? true:false">已完成</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="dialogStatus === 'edit' || temp.principal"
                            :label="$t('terminal.principal') + ' :'"
                            prop="principal">
                <el-input v-model="temp.principal"
                          :readonly="dialogStatus !== 'edit'? true:false"></el-input>
              </el-form-item>
              <el-form-item v-if="dialogStatus === 'edit' || temp.remark"
                            :label="$t('public.remark') + ' :'"
                            prop="remark">
                <el-input type="textarea"
                          v-model="temp.remark"
                          :autosize="{ minRows: 2, maxRows: 6}"
                          placeholder="请输入内容"
                          :readonly="dialogStatus !== 'edit'?true:false">
                </el-input>
              </el-form-item>
            </div>
          </div>
        </el-form>
        <div slot="footer"
             class="dialog-footer between-space">
          <div>
            <el-button v-show="dialogStatus === 'read' && temp.equipment_status !== 2"
                       type="primary"
                       @click="dialogStatus = 'edit'">{{ $t("table.dealWith") }}</el-button>
          </div>
          <div>
            <el-button @click="dialogFormVisible = false">{{
              $t("table.cancel")
            }}</el-button>
            <el-button v-if="dialogStatus == 'create'"
                       type="primary"
                       :disabled="!createDisabled"
                       @click="createData">{{ $t("table.confirm") }}</el-button>
            <el-button v-else-if="dialogStatus == 'edit'"
                       type="primary"
                       :disabled="!updateDisabled"
                       @click="updateData">{{ $t("table.confirm") }}</el-button>
            <el-button v-else
                       type="primary"
                       @click="dialogFormVisible = false">{{ $t("table.confirm") }}</el-button>
          </div>
        </div>
      </el-dialog>
      <el-dialog title="图片预览"
                 :visible.sync="outerVisible">
        <div class="picture-preview">
          <el-image style="width: 100px; height: 100px"
                    :src="temp.equipment_pic"
                    fit="contain"></el-image>
        </div>
      </el-dialog>
    </div>
  </div>
</template>
<script type="text/javascript">
import dropDownSelect from "@/views/select/dropDownSelect"; // 分页选择控件
import { getToken } from "@/utils/auth";
export default {
  name: "Itoc",
  components: {
    "drop-down-select": dropDownSelect
  },
  data() {
    const validateName = (rule, value, callback) => {
      // return false
      if (value.length > 0) {
        if (value.length > 20) {
          callback(new Error("名称长度不能大于20个字符"));
        } else {
          var reg = /^(?!(\d+)$)(?!(\_+)$)[\u4e00-\u9fff\w]+$/; /* 定义验证表达式 */
          if (reg.test(value)) {
            /* 进行验证 */
            callback();
          } else {
            callback(
              new Error("名称只能包含汉字、英文、“_”和数字且不为纯数字或纯符号")
            );
          }
        }
      } else {
        callback(new Error("请填写名称"));
      }
    };
    return {
      showSearchItem: false,
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      statusOptions: [{
        value: 1,
        label: '系统产生'
      }, {
        value: 2,
        label: '手动添加'
      }],
      typeOptions: [{
        value: 1,
        label: '硬件故障'
      }, {
        value: 2,
        label: '系统故障'
      }, {
        value: 3,
        label: '网络故障'
      }, {
        value: 4,
        label: '其他故障'
      }],
      listQuery: {
        page: 1,
        limit: 20,
        equipment_name: "",
        itoc_name: "",
        type: undefined,
        maintain_name: ""
      },
      temp: {
        id: undefined,
        equipment_id: undefined,
        type: undefined,
        malfunction_level: undefined,
        malfunction_time: "",
        describe: "",
        equipment_pic: "",
        principal: "",
        equipment_status: "",
        remark: ""
      },
      dialogFormVisible: false,
      outerVisible: false,
      dialogStatus: "",
      textMap: {
        edit: "处理",
        create: "添加",
        review: "审核",
        read: "查看"
      },
      rules: {
        name: [{ required: true, trigger: "blur", validator: validateName }],
        equipment_id: [{ required: true, message: "请选择终端名称", trigger: "change" }],
        type: [{ required: true, message: "请选择故障类型", trigger: "change" }],
        malfunction_level: [{ required: true, message: "请选择故障级别", trigger: "change" }],
        malfunction_time: [{ required: true, message: "请选择故障时间", trigger: "change" }],
        equipment_status: [{ required: true, message: "请选择维修状态", trigger: "change" }],
        principal: [{ required: true, message: "请填写处理人名称", trigger: "change" }]
      },
      createDisabled: true,
      updateDisabled: true,
      brandOptions: [],
      brandCount: undefined,
      terminalOptions: [],
      terminalCount: undefined,
      sortOptions: [],
      sortCount: undefined,
      pageSize: 20,
      optionProps: {
        value: 'id',
        label: 'name'
      }
    };
  },
  created() {
    const token = getToken()
    if (token && !this.$store.state.socket.loginTransition && !this.$store.state.socket.loginAccount) {
      this.tokenLogin(token)
    }
    this.getList();
  },
  methods: {
    tokenLogin(token) {
      const path = {
        app: "wxadmin",
        api: "api_wxadmin_admin_keepLogin",
        version: "1.0",
        type: 2,
        data: {
          token: token
        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        this.socketData(res);
      });
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleSizeChange(val) {
      this.listQuery.limit = val;
      this.getList();
    },
    handleCurrentChange(val) {
      this.listQuery.page = val;
      this.getList();
    },
    handleRefresh() {
      this.listQuery = {
        page: 1,
        limit: 20,
        equipment_name: "",
        itoc_name: "",
        type: undefined,
        maintain_name: ""
      };
      this.getList();
    },
    searchItem() {
      if (this.showSearchItem === true) {
        this.showSearchItem = false;
      } else {
        this.showSearchItem = true;
      }
    },
    // 获取故障列表
    getList() {
      this.listLoading = true;
      const data = {
        rows: this.listQuery.limit,
        page: this.listQuery.page,
        type: this.listQuery.type ? this.listQuery.type : "",
        equipment_name: this.listQuery.equipment_name ? this.listQuery.equipment_name : "",
        itoc_name: this.listQuery.itoc_name ? this.listQuery.itoc_name : "",
        merchant_name: this.listQuery.merchant_name ? this.listQuery.merchant_name : ""
      };
      const path = {
        app: "equipment",
        api: "api_equipment_malfunction_getList",
        version: "1.0",
        data: data
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },
    // 打开查看弹窗
    handleRead(row) {
      this.temp = Object.assign({}, row); // copy obj
      this.dialogStatus = "read";
      this.dialogFormVisible = true;
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        equipment_id: undefined,
        type: undefined,
        malfunction_level: undefined,
        malfunction_time: "",
        describe: "",
        equipment_pic: ""
      };
    },
    // 更新数据
    upData() {
      const data = {
        id: this.temp.id ? this.temp.id : "",
        equipment_id: this.temp.equipment_id ? this.temp.equipment_id : "",
        type: this.temp.type ? this.temp.type : "",
        malfunction_level: this.temp.malfunction_level ? this.temp.malfunction_level : "",
        malfunction_time: this.temp.malfunction_time ? this.temp.malfunction_time : "",
        describe: this.temp.describe ? this.temp.describe : "",
        equipment_pic: this.temp.equipment_pic ? this.temp.equipment_pic : "",
        principal: this.temp.principal ? this.temp.principal : "",
        equipment_status: this.temp.equipment_status ? this.temp.equipment_status : "",
        remark: this.temp.remark ? this.temp.remark : ""
      };
      return data;
    },
    // 提交故障信息
    createData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.createDisabled) {
            this.createDisabled = false;
            const data = this.upData();
            const path = {
              app: "user",
              api: "api_equipment_malfunction_add",
              version: "1.0",
              type: 2,
              data: data
            };
            this.socketApi.sendSock(JSON.stringify(path), res => {
              if (res) {
                this.socketData(res);
              }
              setTimeout(() => {
                this.createDisabled = true;
              }, 1000);
            });
          }
        }
      });
    },
    // 处理故障信息
    updateData() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          if (this.updateDisabled) {
            this.updateDisabled = false;
            const data = this.upData();
            const path = {
              app: "equipment",
              api: "api_equipment_malfunction_edit",
              version: "1.0",
              data: data
            };
            this.socketApi.sendSock(JSON.stringify(path), res => {
              if (res) {
                this.socketData(res);
              }
              setTimeout(() => {
                this.updateDisabled = true;
              }, 1000);
            });
          }
        }
      });
    },
    updatePicture(element, name) {
      const video = new FormData();
      video.append("video", element.file);
      const index = element.file.name.lastIndexOf(".");
      const suffix = element.file.name.substr(index + 1).toLowerCase();
      if (this.imageFile.indexOf(suffix) !== -1) {
        this.updateFile(video, result => {
          if (result.data.code === 0) {
            this.$message.error(result.data.message);
          } else {
            this.temp[name] = result.data.data.video_url;
          }
        });
      } else {
        this.$message.error("请上传图片文件");
        return false;
      }
    },
    changPicture(name) {
      this.$confirm("是否删除该图片, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          const index = this.temp[name].lastIndexOf("/");
          const str = this.temp[name].substring(
            index + 1,
            this.temp[name].length
          );
          const video_name = { video_name: str };
          this.deleteFile(video_name, result => {
            if (result.data.code === 0) {
              this.$message.error(result.data.message);
            } else {
              this.temp[name] = "";
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 预览图片
    previewPicture(name) {
      this.outerVisible = true;
    },
    // 终端选择
    getTerminal(pageNumber, search, name) {
      const path = {
        app: "equipment",
        api: "api_equipment_index_getList",
        version: "1.0",
        data: {
          rows: this.pageSize,
          page: pageNumber || 1,
          name: search || "",
          returnType: name || ""
        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    // 选择分类
    chooseSort(e) {
      const nodeData = this.$refs['cascaderSort'].getCheckedNodes()[0].data
      this.temp.category_id = nodeData.id;
      this.temp.category_name = nodeData.name;
    },
    // 供货商选择
    getSupplier(pageNumber, search, name) {
      const path = {
        app: "common",
        api: "api_archives_supplier_getList",
        version: "1.0",
        data: {
          rows: this.pageSize,
          page: pageNumber || 1,
          name: search || "",
          returnType: name || ""
        }
      };
      this.socketApi.sendSock(JSON.stringify(path), res => {
        if (res) {
          this.socketData(res);
        }
      });
    },
    choose(data, name) {
      if (name === 'terminal') {
        this.temp.equipment_id = data.id;
        this.temp.equipment_name = data.name;
      }
    },
    remove(data, name) {
      if (name === 'terminal') {
        this.temp.equipment_id = undefined;
        this.temp.equipment_name = "";
      }
    },
    socketData(res) {
      if (res !== '{"type":"ping"}') {
        const resj = JSON.parse(res);
        if (resj.code === -1) {
          this.$message.error(resj.message);
        } else {
          if (resj.api === "api_wxadmin_admin_keepLogin") {
            this.$store.dispatch("loginTransition", true);
            this.socketApi.sendCache(res => {
              this.socketData(res);
            })
          } else if (resj.api === "api_equipment_malfunction_getList") {
            this.total = resj.count;
            this.list = resj.data;
            this.listLoading = false;
          } else if (resj.api === "api_equipment_malfunction_add") {
            this.$notify({
              title: "成功",
              message: "添加成功",
              type: "success",
              duration: 2000
            });
            this.dialogFormVisible = false;
            this.getList();
          } else if (resj.api === "api_equipment_malfunction_edit") {
            this.$notify({
              title: "成功",
              message: "处理成功",
              type: "success",
              duration: 2000
            });
            this.dialogFormVisible = false;
            this.getList();
          } else if (resj.api === "api_archives_category_getList") {
            this.sortOptions = resj.data;
          } else if (resj.api === "api_equipment_index_getList" && resj.type === "getTerminal") {
            this.terminalOptions = resj.data;
            this.terminalCount = resj.count;
          } else if (resj.api === "api_equipment_index_getList" && resj.type === "addTerminal") {
            this.terminalOptions = this.terminalOptions.concat(resj.data);
          }
        }
      }
    }
  }
};
</script>
